//! # 部署命令
//!
//! 用于部署服务到目标环境，支持 Docker 和 Kubernetes

use crate::config::CliConfig;
use crate::error::{CliError, CliResult};
use clap::Args;
use colored::*;
use console::Emoji;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::fs;
use tokio::process::Command;
use tracing::{info, warn, error};

static ROCKET: Emoji<'_, '_> = Emoji("🚀 ", "");
static TRUCK: Emoji<'_, '_> = Emoji("🚚 ", "");
static GEAR: Emoji<'_, '_> = Emoji("⚙️ ", "");
static CHECK: Emoji<'_, '_> = Emoji("✅ ", "");
static CROSS: Emoji<'_, '_> = Emoji("❌ ", "");

/// 部署命令参数
#[derive(Args, Debug)]
pub struct DeployArgs {
    /// 目标环境
    #[arg(short, long, default_value = "development")]
    pub environment: String,

    /// 使用 Docker 部署
    #[arg(long)]
    pub docker: bool,

    /// 使用 Kubernetes 部署
    #[arg(long)]
    pub kubernetes: bool,

    /// 使用 Helm 部署
    #[arg(long)]
    pub helm: bool,

    /// 预览部署配置（不实际执行）
    #[arg(long)]
    pub dry_run: bool,

    /// 构建镜像标签
    #[arg(long)]
    pub tag: Option<String>,

    /// 配置文件路径
    #[arg(long)]
    pub config_file: Option<PathBuf>,

    /// 强制重新构建
    #[arg(long)]
    pub force_rebuild: bool,

    /// 跳过测试
    #[arg(long)]
    pub skip_tests: bool,
}

/// 部署配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeploymentConfig {
    /// 项目名称
    pub name: String,
    /// 环境配置
    pub environment: EnvironmentConfig,
    /// Docker 配置
    pub docker: DockerDeployConfig,
    /// Kubernetes 配置
    pub kubernetes: KubernetesDeployConfig,
}

/// 环境配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentConfig {
    /// 环境名称
    pub name: String,
    /// 部署目标
    pub target: DeployTarget,
    /// 环境变量
    pub env_vars: HashMap<String, String>,
    /// 资源限制
    pub resources: ResourceConfig,
}

/// 部署目标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DeployTarget {
    /// 本地部署
    Local,
    /// Docker 部署
    Docker,
    /// Kubernetes 部署
    Kubernetes,
}

/// 资源配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceConfig {
    /// CPU 限制
    pub cpu_limit: Option<String>,
    /// 内存限制
    pub memory_limit: Option<String>,
    /// 副本数量
    pub replicas: Option<u32>,
}

/// Docker 部署配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DockerDeployConfig {
    /// 镜像名称
    pub image_name: String,
    /// 镜像标签
    pub tag: String,
    /// 构建参数
    pub build_args: HashMap<String, String>,
    /// 运行时参数
    pub run_args: Vec<String>,
    /// 端口映射
    pub ports: Vec<String>,
    /// 卷挂载
    pub volumes: Vec<String>,
}

/// Kubernetes 部署配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KubernetesDeployConfig {
    /// 命名空间
    pub namespace: String,
    /// 部署名称
    pub deployment_name: String,
    /// 服务名称
    pub service_name: String,
    /// 配置映射
    pub config_maps: Vec<String>,
    /// 密钥
    pub secrets: Vec<String>,
}

/// 执行部署命令
pub async fn execute(args: DeployArgs, config: CliConfig) -> CliResult<()> {
    println!("{} {}开始部署到环境: {}", ROCKET, "开始".bright_green().bold(), args.environment.bright_yellow());

    // 验证项目环境
    validate_project_environment().await?;

    // 加载部署配置
    let deploy_config = load_deployment_config(&args, &config).await?;

    // 预检查
    pre_deployment_checks(&deploy_config, &args).await?;

    // 构建项目
    if !args.skip_tests {
        run_tests().await?;
    }
    build_project(&args).await?;

    // 根据部署目标执行部署
    match deploy_config.environment.target {
        DeployTarget::Local => deploy_local(&deploy_config, &args).await?,
        DeployTarget::Docker => deploy_docker(&deploy_config, &args).await?,
        DeployTarget::Kubernetes => {
            if args.helm {
                deploy_helm(&deploy_config, &args).await?
            } else {
                deploy_kubernetes(&deploy_config, &args).await?
            }
        }
    }

    println!("{} {}部署完成！", CHECK, "成功".bright_green().bold());
    show_deployment_info(&deploy_config)?;

    Ok(())
}

// =============================================================================
// 部署实现函数
// =============================================================================

/// 验证项目环境
async fn validate_project_environment() -> CliResult<()> {
    info!("验证项目环境");
    
    // 检查 Cargo.toml
    if !Path::new("Cargo.toml").exists() {
        return Err(CliError::validation("当前目录不是一个 Rust 项目"));
    }

    // 检查是否为 RustCloud 项目
    let cargo_content = fs::read_to_string("Cargo.toml").await?;
    if !cargo_content.contains("rustcloud") {
        warn!("当前项目不是 RustCloud 项目，将使用通用部署配置");
    }

    Ok(())
}

/// 加载部署配置
async fn load_deployment_config(args: &DeployArgs, config: &CliConfig) -> CliResult<DeploymentConfig> {
    info!("加载部署配置");
    
    // 尝试从指定的配置文件加载
    if let Some(config_file) = &args.config_file {
        if config_file.exists() {
            let content = fs::read_to_string(config_file).await?;
            let deploy_config: DeploymentConfig = toml::from_str(&content)
                .map_err(|e| CliError::general(format!("解析配置文件失败: {}", e)))?;
            return Ok(deploy_config);
        }
    }

    // 尝试从默认位置加载
    let default_config_path = format!("deploy/{}.toml", args.environment);
    if Path::new(&default_config_path).exists() {
        let content = fs::read_to_string(&default_config_path).await?;
        let deploy_config: DeploymentConfig = toml::from_str(&content)
            .map_err(|e| CliError::general(format!("解析配置文件失败: {}", e)))?;
        return Ok(deploy_config);
    }

    // 生成默认配置
    Ok(generate_default_config(args, config).await?)
}

/// 生成默认部署配置
async fn generate_default_config(args: &DeployArgs, config: &CliConfig) -> CliResult<DeploymentConfig> {
    let cargo_toml = fs::read_to_string("Cargo.toml").await?;
    let project_name = extract_project_name(&cargo_toml)?;
    
    let target = if args.kubernetes || args.helm {
        DeployTarget::Kubernetes
    } else if args.docker {
        DeployTarget::Docker
    } else {
        DeployTarget::Local
    };

    let deploy_config = DeploymentConfig {
        name: project_name.clone(),
        environment: EnvironmentConfig {
            name: args.environment.clone(),
            target,
            env_vars: get_default_env_vars(&args.environment),
            resources: ResourceConfig {
                cpu_limit: Some("500m".to_string()),
                memory_limit: Some("512Mi".to_string()),
                replicas: Some(if args.environment == "production" { 3 } else { 1 }),
            },
        },
        docker: DockerDeployConfig {
            image_name: format!("{}/{}", config.deploy.docker.namespace, project_name),
            tag: args.tag.clone().unwrap_or_else(|| "latest".to_string()),
            build_args: HashMap::new(),
            run_args: vec!["-d".to_string()],
            ports: vec!["8080:8080".to_string()],
            volumes: Vec::new(),
        },
        kubernetes: KubernetesDeployConfig {
            namespace: if args.environment == "production" { "prod".to_string() } else { "dev".to_string() },
            deployment_name: project_name.clone(),
            service_name: format!("{}-service", project_name),
            config_maps: Vec::new(),
            secrets: Vec::new(),
        },
    };

    Ok(deploy_config)
}

/// 预检查
async fn pre_deployment_checks(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("执行部署前检查");
    
    match config.environment.target {
        DeployTarget::Docker => {
            check_docker_available().await?
        }
        DeployTarget::Kubernetes => {
            check_kubernetes_available().await?
        }
        DeployTarget::Local => {}
    }

    if args.dry_run {
        println!("{} {}预览模式，不会实际执行部署", GEAR, "信息".bright_blue());
    }

    Ok(())
}

/// 检查 Docker 是否可用
async fn check_docker_available() -> CliResult<()> {
    let output = Command::new("docker")
        .arg("--version")
        .output()
        .await?;

    if !output.status.success() {
        return Err(CliError::general("Docker 不可用，请安装 Docker"));
    }

    info!("Docker 检查通过");
    Ok(())
}

/// 检查 Kubernetes 是否可用
async fn check_kubernetes_available() -> CliResult<()> {
    let output = Command::new("kubectl")
        .arg("version")
        .arg("--client")
        .output()
        .await?;

    if !output.status.success() {
        return Err(CliError::general("kubectl 不可用，请安装 kubectl"));
    }

    info!("Kubernetes 检查通过");
    Ok(())
}

/// 运行测试
async fn run_tests() -> CliResult<()> {
    info!("运行项目测试");
    println!("{} 运行测试...", GEAR);

    let output = Command::new("cargo")
        .arg("test")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("测试失败: {}", stderr)));
    }

    println!("{} 测试通过", CHECK);
    Ok(())
}

/// 构建项目
async fn build_project(args: &DeployArgs) -> CliResult<()> {
    info!("构建项目");
    println!("{} 构建项目...", GEAR);

    let mut cmd = Command::new("cargo");
    cmd.arg("build").arg("--release");

    if args.force_rebuild {
        cmd.arg("--force");
    }

    let output = cmd
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("构建失败: {}", stderr)));
    }

    println!("{} 构建完成", CHECK);
    Ok(())
}

// =============================================================================
// 部署实现
// =============================================================================

/// 本地部署
async fn deploy_local(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("执行本地部署");
    println!("{} 本地部署...", TRUCK);

    if args.dry_run {
        println!("📄 预览本地部署配置:");
        println!("  项目名称: {}", config.name);
        println!("  环境: {}", config.environment.name);
        println!("  命令: cargo run --release");
        return Ok(());
    }

    // 设置环境变量
    let mut cmd = Command::new("cargo");
    cmd.arg("run").arg("--release");
    
    for (key, value) in &config.environment.env_vars {
        cmd.env(key, value);
    }

    println!("启动本地服务...");
    let child = cmd.spawn()?;
    
    println!("{} 本地服务已启动，PID: {}", CHECK, child.id().unwrap_or(0));
    Ok(())
}

/// Docker 部署
async fn deploy_docker(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("执行 Docker 部署");
    println!("{} Docker 部署...", TRUCK);

    // 构建 Docker 镜像
    build_docker_image(config, args).await?;

    if args.dry_run {
        println!("📄 预览 Docker 部署配置:");
        println!("  镜像名称: {}:{}", config.docker.image_name, config.docker.tag);
        println!("  端口映射: {:?}", config.docker.ports);
        println!("  运行参数: {:?}", config.docker.run_args);
        return Ok(());
    }

    // 运行 Docker 容器
    run_docker_container(config).await?;

    println!("{} Docker 部署完成", CHECK);
    Ok(())
}

/// 构建 Docker 镜像
async fn build_docker_image(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("构建 Docker 镜像");
    println!("{} 构建 Docker 镜像...", GEAR);

    // 生成 Dockerfile
    generate_dockerfile(config).await?;

    let image_tag = format!("{}:{}", config.docker.image_name, config.docker.tag);
    
    let mut cmd = Command::new("docker");
    cmd.arg("build")
        .arg("-t")
        .arg(&image_tag)
        .arg(".");

    // 添加构建参数
    for (key, value) in &config.docker.build_args {
        cmd.arg("--build-arg").arg(format!("{}={}", key, value));
    }

    if args.force_rebuild {
        cmd.arg("--no-cache");
    }

    let output = cmd.output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("Docker 镜像构建失败: {}", stderr)));
    }

    println!("{} Docker 镜像构建完成: {}", CHECK, image_tag);
    Ok(())
}

/// 生成 Dockerfile
async fn generate_dockerfile(config: &DeploymentConfig) -> CliResult<()> {
    if Path::new("Dockerfile").exists() {
        info!("Dockerfile 已存在，跳过生成");
        return Ok(());
    }

    let dockerfile_content = format!(r#"# 自动生成的 Dockerfile
FROM rust:alpine as builder

WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src

RUN cargo build --release

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/

COPY --from=builder /app/target/release/{} ./app

EXPOSE 8080

CMD ["./app"]
"#, config.name);

    fs::write("Dockerfile", dockerfile_content).await?;
    info!("生成 Dockerfile 完成");
    Ok(())
}

/// 运行 Docker 容器
async fn run_docker_container(config: &DeploymentConfig) -> CliResult<()> {
    let image_tag = format!("{}:{}", config.docker.image_name, config.docker.tag);
    let container_name = format!("{}-{}", config.name, config.environment.name);

    // 停止并删除旧容器
    let _ = Command::new("docker")
        .args(["stop", &container_name])
        .output()
        .await;
    let _ = Command::new("docker")
        .args(["rm", &container_name])
        .output()
        .await;

    let mut cmd = Command::new("docker");
    cmd.arg("run")
        .arg("--name")
        .arg(&container_name);

    // 添加运行参数
    for arg in &config.docker.run_args {
        cmd.arg(arg);
    }

    // 添加端口映射
    for port in &config.docker.ports {
        cmd.arg("-p").arg(port);
    }

    // 添加卷挂载
    for volume in &config.docker.volumes {
        cmd.arg("-v").arg(volume);
    }

    // 添加环境变量
    for (key, value) in &config.environment.env_vars {
        cmd.arg("-e").arg(format!("{}={}", key, value));
    }

    cmd.arg(&image_tag);

    let output = cmd.output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("Docker 容器启动失败: {}", stderr)));
    }

    let container_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
    println!("{} Docker 容器已启动: {}", CHECK, container_id);
    Ok(())
}

/// Kubernetes 部署
async fn deploy_kubernetes(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("执行 Kubernetes 部署");
    println!("{} Kubernetes 部署...", TRUCK);

    // 生成 Kubernetes 配置文件
    generate_kubernetes_manifests(config).await?;

    if args.dry_run {
        println!("📄 预览 Kubernetes 部署配置:");
        println!("  命名空间: {}", config.kubernetes.namespace);
        println!("  部署名称: {}", config.kubernetes.deployment_name);
        println!("  服务名称: {}", config.kubernetes.service_name);
        return Ok(());
    }

    // 应用 Kubernetes 配置
    apply_kubernetes_manifests(config).await?;

    println!("{} Kubernetes 部署完成", CHECK);
    Ok(())
}

/// Helm 部署
async fn deploy_helm(config: &DeploymentConfig, args: &DeployArgs) -> CliResult<()> {
    info!("执行 Helm 部署");
    println!("{} Helm 部署...", TRUCK);

    // 生成 Helm Chart
    generate_helm_chart(config).await?;

    if args.dry_run {
        println!("📄 预览 Helm 部署配置:");
        println!("  Chart 名称: {}", config.name);
        println!("  发布名称: {}-{}", config.name, config.environment.name);
        return Ok(());
    }

    // 执行 Helm 部署
    execute_helm_deployment(config).await?;

    println!("{} Helm 部署完成", CHECK);
    Ok(())
}

/// 生成 Kubernetes 配置文件
async fn generate_kubernetes_manifests(config: &DeploymentConfig) -> CliResult<()> {
    info!("生成 Kubernetes 配置文件");
    
    fs::create_dir_all("k8s").await?;

    // 生成 Deployment
    let deployment_yaml = generate_deployment_yaml(config);
    fs::write("k8s/deployment.yaml", deployment_yaml).await?;

    // 生成 Service
    let service_yaml = generate_service_yaml(config);
    fs::write("k8s/service.yaml", service_yaml).await?;

    // 生成 ConfigMap（如果需要）
    if !config.environment.env_vars.is_empty() {
        let configmap_yaml = generate_configmap_yaml(config);
        fs::write("k8s/configmap.yaml", configmap_yaml).await?;
    }

    println!("{} Kubernetes 配置文件生成完成", CHECK);
    Ok(())
}

/// 应用 Kubernetes 配置
async fn apply_kubernetes_manifests(config: &DeploymentConfig) -> CliResult<()> {
    // 创建命名空间（如果不存在）
    let _ = Command::new("kubectl")
        .args(["create", "namespace", &config.kubernetes.namespace])
        .output()
        .await;

    // 应用配置文件
    let output = Command::new("kubectl")
        .args(["apply", "-f", "k8s/", "-n", &config.kubernetes.namespace])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("Kubernetes 配置应用失败: {}", stderr)));
    }

    println!("{} Kubernetes 配置应用成功", CHECK);
    Ok(())
}

/// 生成 Helm Chart
async fn generate_helm_chart(config: &DeploymentConfig) -> CliResult<()> {
    info!("生成 Helm Chart");
    
    let chart_dir = format!("helm/{}", config.name);
    fs::create_dir_all(&format!("{}/templates", chart_dir)).await?;

    // 生成 Chart.yaml
    let chart_yaml = generate_chart_yaml(config);
    fs::write(format!("{}/Chart.yaml", chart_dir), chart_yaml).await?;

    // 生成 values.yaml
    let values_yaml = generate_values_yaml(config);
    fs::write(format!("{}/values.yaml", chart_dir), values_yaml).await?;

    // 生成模板文件
    let deployment_template = generate_helm_deployment_template();
    fs::write(format!("{}/templates/deployment.yaml", chart_dir), deployment_template).await?;

    let service_template = generate_helm_service_template();
    fs::write(format!("{}/templates/service.yaml", chart_dir), service_template).await?;

    println!("{} Helm Chart 生成完成", CHECK);
    Ok(())
}

/// 执行 Helm 部署
async fn execute_helm_deployment(config: &DeploymentConfig) -> CliResult<()> {
    let release_name = format!("{}-{}", config.name, config.environment.name);
    let chart_path = format!("helm/{}", config.name);

    let output = Command::new("helm")
        .args([
            "upgrade",
            "--install",
            &release_name,
            &chart_path,
            "--namespace",
            &config.kubernetes.namespace,
            "--create-namespace",
        ])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CliError::general(format!("Helm 部署失败: {}", stderr)));
    }

    println!("{} Helm 部署成功", CHECK);
    Ok(())
}

// =============================================================================
// YAML 生成函数
// =============================================================================

/// 生成 Deployment YAML
fn generate_deployment_yaml(config: &DeploymentConfig) -> String {
    let image_tag = format!("{}:{}", config.docker.image_name, config.docker.tag);
    
    format!(r#"apiVersion: apps/v1
kind: Deployment
metadata:
  name: {}
  namespace: {}
spec:
  replicas: {}
  selector:
    matchLabels:
      app: {}
  template:
    metadata:
      labels:
        app: {}
    spec:
      containers:
      - name: {}
        image: {}
        ports:
        - containerPort: 8080
        resources:
          limits:
            cpu: {}
            memory: {}
          requests:
            cpu: 100m
            memory: 128Mi
        env:
        - name: RUST_LOG
          value: "info"
"#,
        config.kubernetes.deployment_name,
        config.kubernetes.namespace,
        config.environment.resources.replicas.unwrap_or(1),
        config.name,
        config.name,
        config.name,
        image_tag,
        config.environment.resources.cpu_limit.as_ref().unwrap_or(&"500m".to_string()),
        config.environment.resources.memory_limit.as_ref().unwrap_or(&"512Mi".to_string())
    )
}

/// 生成 Service YAML
fn generate_service_yaml(config: &DeploymentConfig) -> String {
    format!(r#"apiVersion: v1
kind: Service
metadata:
  name: {}
  namespace: {}
spec:
  selector:
    app: {}
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
  type: ClusterIP
"#,
        config.kubernetes.service_name,
        config.kubernetes.namespace,
        config.name
    )
}

/// 生成 ConfigMap YAML
fn generate_configmap_yaml(config: &DeploymentConfig) -> String {
    let mut env_vars = String::new();
    for (key, value) in &config.environment.env_vars {
        env_vars.push_str(&format!("  {}: \"{}\"
", key, value));
    }
    
    format!(r#"apiVersion: v1
kind: ConfigMap
metadata:
  name: {}-config
  namespace: {}
data:
{}
"#,
        config.name,
        config.kubernetes.namespace,
        env_vars
    )
}

/// 生成 Chart.yaml
fn generate_chart_yaml(config: &DeploymentConfig) -> String {
    format!(r#"apiVersion: v2
name: {}
description: A Helm chart for {}
type: application
version: 0.1.0
appVersion: \"{}\"
"#,
        config.name,
        config.name,
        config.docker.tag
    )
}

/// 生成 values.yaml
fn generate_values_yaml(config: &DeploymentConfig) -> String {
    format!(r#"# Default values for {}.
replicaCount: {}

image:
  repository: {}
  tag: \"{}\"
  pullPolicy: IfNotPresent

service:
  type: ClusterIP
  port: 80
  targetPort: 8080

resources:
  limits:
    cpu: {}
    memory: {}
  requests:
    cpu: 100m
    memory: 128Mi

env: {{
"#,
        config.name,
        config.environment.resources.replicas.unwrap_or(1),
        config.docker.image_name,
        config.docker.tag,
        config.environment.resources.cpu_limit.as_ref().unwrap_or(&"500m".to_string()),
        config.environment.resources.memory_limit.as_ref().unwrap_or(&"512Mi".to_string())
    )
}

/// 生成 Helm Deployment 模板
fn generate_helm_deployment_template() -> String {
    r#"apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "chart.fullname" . }}
  labels:
    {{- include "chart.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      {{- include "chart.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "chart.selectorLabels" . | nindent 8 }}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{ .Values.service.targetPort }}
              protocol: TCP
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
"#.to_string()
}

/// 生成 Helm Service 模板
fn generate_helm_service_template() -> String {
    r#"apiVersion: v1
kind: Service
metadata:
  name: {{ include "chart.fullname" . }}
  labels:
    {{- include "chart.labels" . | nindent 4 }}
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: http
      protocol: TCP
      name: http
  selector:
    {{- include "chart.selectorLabels" . | nindent 4 }}
"#.to_string()
}

// =============================================================================
// 工具函数
// =============================================================================

/// 提取项目名称
fn extract_project_name(cargo_content: &str) -> CliResult<String> {
    for line in cargo_content.lines() {
        if line.trim().starts_with("name") {
            if let Some(name) = line.split('=').nth(1) {
                return Ok(name.trim().trim_matches('"').to_string());
            }
        }
    }
    Err(CliError::general("无法从 Cargo.toml 中提取项目名称"))
}

/// 获取默认环境变量
fn get_default_env_vars(environment: &str) -> HashMap<String, String> {
    let mut env_vars = HashMap::new();
    
    match environment {
        "development" => {
            env_vars.insert("RUST_LOG".to_string(), "debug".to_string());
            env_vars.insert("DATABASE_URL".to_string(), "postgres://localhost/myapp_dev".to_string());
        }
        "staging" => {
            env_vars.insert("RUST_LOG".to_string(), "info".to_string());
            env_vars.insert("DATABASE_URL".to_string(), "postgres://staging-db/myapp".to_string());
        }
        "production" => {
            env_vars.insert("RUST_LOG".to_string(), "warn".to_string());
            env_vars.insert("DATABASE_URL".to_string(), "postgres://prod-db/myapp".to_string());
        }
        _ => {
            env_vars.insert("RUST_LOG".to_string(), "info".to_string());
        }
    }
    
    env_vars
}

/// 显示部署信息
fn show_deployment_info(config: &DeploymentConfig) -> CliResult<()> {
    println!();
    println!("📊 部署信息:");
    println!("  项目名称: {}", config.name.bright_blue());
    println!("  环境: {}", config.environment.name.bright_yellow());
    println!("  部署目标: {:?}", config.environment.target);
    
    match config.environment.target {
        DeployTarget::Local => {
            println!("  访问地址: {}", "http://localhost:8080".bright_green());
        }
        DeployTarget::Docker => {
            println!("  Docker 镜像: {}:{}", config.docker.image_name.bright_cyan(), config.docker.tag.bright_cyan());
            println!("  访问地址: {}", "http://localhost:8080".bright_green());
        }
        DeployTarget::Kubernetes => {
            println!("  命名空间: {}", config.kubernetes.namespace.bright_cyan());
            println!("  部署名称: {}", config.kubernetes.deployment_name.bright_cyan());
            println!("  服务名称: {}", config.kubernetes.service_name.bright_cyan());
        }
    }
    
    println!();
    println!("📝 后续操作:");
    match config.environment.target {
        DeployTarget::Local => {
            println!("  查看日志: {}", "tail -f logs/app.log".bright_blue());
        }
        DeployTarget::Docker => {
            println!("  查看容器: {}", format!("docker ps | grep {}", config.name).bright_blue());
            println!("  查看日志: {}", format!("docker logs {}-{} -f", config.name, config.environment.name).bright_blue());
        }
        DeployTarget::Kubernetes => {
            println!("  查看 Pod: {}", format!("kubectl get pods -n {}", config.kubernetes.namespace).bright_blue());
            println!("  查看日志: {}", format!("kubectl logs -f deployment/{} -n {}", config.kubernetes.deployment_name, config.kubernetes.namespace).bright_blue());
        }
    }
    
    Ok(())
}